import paramiko
import os
import getpass
class MySshClient:
    def __init__(self, ssh_client):
        self.ssh_client = ssh_client
        
    def exec_command(self, cmd):
        try:
            stdin, stdout, stderr = self.ssh_client.exec_command(cmd)
            return stdin, stdout, stderr
        except Exception as e:
            print(f"Error executing command {cmd}: {e}")
            
    def __enter__(self):
        return self
        
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.ssh_client.close()
        
def connect(host, port, username, password):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.WarningPolicy())
        
    try:
        ssh.load_system_host_keys()
        ssh.connect(host, port, username, password,timeout=3)
    except paramiko.AuthenticationException:
        raise Exception(f"在主机 {host}连接失败,请检查你的参数")
    except paramiko.SSHException as e:
        raise Exception(f"Error connecting to {host}: {e}")
    except paramiko.BadHostKeyException as e:
        raise Exception(f"Host key for {host} could not be verified: {e}")
    except Exception as e:
        raise Exception(f" 连接到{host}:{port}: {e}超时")
        
    return ssh


if __name__ == '__main__':   
    host = input("Host: 请输入主机名")
    port = int(input("Port: 默认为22")or 22) 
    username = input("Username: 请输入用户名")  
    password = getpass.getpass("Password: 请输入密码")
    print('连接中...........')
    ssh = connect(host, port, username, password,)
    
    with MySshClient(ssh) as client:
        stdin, stdout, stderr = client.exec_command("ls -l")
        with stdout:
            print(stdout.read().decode())
        with stderr:
            print(stderr.read().decode())